package com.ssish.saas.eccs.controller;

import com.ssish.saas.eccs.model.SymUser;
import com.ssish.saas.eccs.model.SymUserExample;
import com.ssish.saas.eccs.service.LoginService;
import com.ssish.saas.eccs.util.JsonResult;
import com.ssish.saas.eccs.util.MD5Util;
import com.ssish.saas.eccs.util.RandomValidateCodeUtil;
import com.ssish.saas.eccs.vo.LoginUserChangeVo;
import com.ssish.saas.eccs.vo.LoginUserVo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Api("eccs登录接口文档")
@RefreshScope
@RestController
@RequestMapping("/login")
public class LoginController extends BaseController {
    @Value("${eccs.user.key}")
    private String userKey;

    @Autowired
    private LoginService loginService;

    @ApiOperation("登录验证")
    @PostMapping("/isValidUserInfo")
    public JsonResult<LoginUserVo> isValidUserInfo(@RequestBody(required = false) LoginUserVo userVo,HttpServletRequest request){
         if(userVo == null){
             return JsonResult.err("用户名或者密码错误",JsonResult.PASSWORD_ERROR);
         }
         if(StringUtils.isBlank(userVo.getUserName())||StringUtils.isBlank(userVo.getPassword())){
             return JsonResult.err("用户名或者密码错误",JsonResult.PASSWORD_ERROR);
         }
         if(StringUtils.isBlank(userVo.getVerificationCode())){
             return JsonResult.err("验证码不正确",JsonResult.VER_CODE);
         }
         //session获取验证码
         String verCode = (String)request.getSession().getAttribute(RandomValidateCodeUtil.ECCS_VALID_CODE_KEY);
         if(!StringUtils.equals(userVo.getVerificationCode(),verCode)){
             return JsonResult.err("验证码不正确",JsonResult.VER_CODE);
         }

         //调登录验证接口
        try {
            //判断登录用户是否存在
            SymUser symUser = loginService.getSymUserInfoById(userVo.getUserName());
            if(symUser == null){
                return JsonResult.err("用户名或者密码错误",JsonResult.PASSWORD_ERROR);
            }
            Boolean isVlaid = loginService.isValidUserInfo(symUser,userVo.getPassword());
            if(!isVlaid){
                return JsonResult.err("用户名或者密码错误",JsonResult.PASSWORD_ERROR);
            }
            request.getSession().removeAttribute(userKey);
            request.getSession().setAttribute(userKey,symUser);
            return JsonResult.ok("登录成功！");
        } catch (Exception e) {
            log.error("客户登录验证接口报错！"+e.getMessage());
            return JsonResult.err("客户登录验证接口报错！",JsonResult.EXCEPTION);
        }
    }

    @ApiOperation("获取验证码接口")
    @GetMapping("/defaultKaptcha")
    public void defaultKaptcha(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
        response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
        randomValidateCode.getRandcode(request, response);//输出验证码图片方法
    }

    @ApiOperation("登录注销接口")
    @GetMapping("/logOut")
    public JsonResult loginOut(HttpServletRequest request){
        try {
            SymUser symUser = (SymUser)request.getSession().getAttribute(userKey);
            if(symUser == null){
                return JsonResult.ok("注销成功！");
            }
            request.getSession().removeAttribute(userKey);
            return JsonResult.ok("注销成功!");
        } catch (Exception e) {
            log.error("注销接口接口报错！"+e.getMessage());
            return JsonResult.err("注销接口接口报错报错！",JsonResult.EXCEPTION);
        }
    }
    
    @ApiOperation("用户密码变更接口")
    @PostMapping("/changPassWord")
    public JsonResult<LoginUserVo>  changPassWord(@RequestBody LoginUserChangeVo userVo){
    	String  usrid=userVo.getUserName();
    	String  oldPassWord=userVo.getOldPassword();
    	String  newPassWord=userVo.getNewPassWord();
    	String  confirmPassword=userVo.getConfirmPassword();
    	int temp=0;
    	if(!newPassWord.equals(confirmPassword)){
    		 return JsonResult.err("新密码和确认密码不一致",JsonResult.EXCEPTION);
    	}
    	SymUser symUser = loginService.getSymUser(usrid,oldPassWord);
    	if(symUser!=null){
    		String  newenPassWord = MD5Util.MD5Encode(newPassWord,"UTF-8");
    		symUser.setPasswd(newenPassWord);
    	    temp=loginService.changePassWord(symUser);
    	    System.out.println("==temp=="+temp);
    	}else{
    		return JsonResult.err("要修改的密码输入不对",JsonResult.EXCEPTION);
    	}
    	
    	if(temp==1){
    		return JsonResult.ok("修改密码成功");
    	}else{
    		return JsonResult.err("修改密码失败",JsonResult.EXCEPTION);
    	}
	 }
    
    
    public boolean checkWhitelist(HttpServletRequest request,SymUser symUser){
    	String iP="";
    	if (request.getHeader("x-forwarded-for") == null) { 
    		iP= request.getRemoteAddr(); 
    	} 
    	System.out.println("=ip="+iP);
    	String ipAddr=symUser.getIpaddr();
    	System.out.println("=ipAddr="+ipAddr);
    	if("".equals(iP)){
    		return false;
    	}
    	if(ipAddr==null||"".equals(ipAddr)){
    		return false;
    	}
    	if(ipAddr.indexOf(iP)!=-1){
    		return true;
    	}else{
    		return false;
    	}
    }
}
